package br.com.infnet.projeto.bloco.dao.impl;

import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import br.com.infnet.projeto.bloco.dao.ContaEspecialDAO;
import br.com.infnet.projeto.bloco.exception.ObjetoNaoEncontradoException;
import br.com.infnet.projeto.bloco.model.ContaEspecial;

public class ContaEspecialDAOImpl implements ContaEspecialDAO {

	private EntityManager entityManager;

	public ContaEspecialDAOImpl(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public long incluir(ContaEspecial contaEspecial) {
		entityManager.persist(contaEspecial);
		return contaEspecial.getId();
	}

	public boolean excluir(ContaEspecial contaEspecial) {
		try {
			ContaEspecial conta = entityManager.getReference(
					ContaEspecial.class, new Long(contaEspecial.getId()));
			entityManager.remove(conta);
			return true;
		} catch (EntityNotFoundException e) {
			return false;
		}
	}

	public boolean alterar(ContaEspecial contaEspecial) {
		try {
			entityManager.getReference(ContaEspecial.class, new Long(
					contaEspecial.getId()));
			entityManager.merge(contaEspecial);
			return true;
		} catch (EntityNotFoundException e) {
			return false;
		}

	}

	public ContaEspecial buscar(long id) throws ObjetoNaoEncontradoException {
		ContaEspecial contaEspecial = (ContaEspecial) entityManager.find(
				ContaEspecial.class, new Long(id));

		if (contaEspecial == null) {
			throw new ObjetoNaoEncontradoException();
		}

		return contaEspecial;
	}

	public ContaEspecial buscarPorNumero(Long numeroConta) throws ObjetoNaoEncontradoException {
		try
		{
			Query query = entityManager.createQuery("select c from ContaEspecial c where c.numero = :numeroConta");
			query.setParameter("numeroConta", numeroConta);
			ContaEspecial contaEspecial = (ContaEspecial) query.getSingleResult();
			return contaEspecial;
		}
		catch(NoResultException e)
		{
			throw new ObjetoNaoEncontradoException();
		}
	}

}
